// pages/search/search.js
import request from "../../utils/request";
let isSend = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholderContent:"",
    hotList:[],// 热搜榜数据
    searchContent:"",// 用户输入的表单数据
    searchList:[],
    historyList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  this.getInitData()
    this.getSearchList()
  },
  // 获取本地搜索历史记录
  getSearchHistory(){
    let histroryList = wx.getStorageSync('searchHistory')
    if(histroryList){
      this.setData({
        histroryList
      })
    }
  },

async getInitData(){
  let placeholderData = await request("/search/default")
  let hotListData = await request("/search/hot/detail")

  this.setData({
    placeholderContent:placeholderData.data.showKeyword,
    hotList:hotListData.data
  })
},
  handleInputChange: function (event) {
    this.setData({
      searchContent: event.detail.value.trim()
    })
    if(isSend){
      return
    }
    isSend = true
    this.getSearchList()
    setTimeout(async () => {
      isSend = false
    }, 300)
  },
  async getSearchList(){
    if(!this.data.searchContent){

      this.setData({
        searchList: []
      })
      return
    }
    let {searchContent,historyList} = this.data
    let searchListData = await request("/search", {keywords: searchContent, limit: 10})
    let index = historyList.indexOf(searchContent)
    if(index !== -1){
      historyList.splice(index,1)
    }
    historyList.unshift(searchContent)

    this.setData({
      searchList: searchListData.result.songs,
      historyList
    })
  wx.setStorageSync("searchHistory", historyList)
  },
  clearSearchContent(){
    this.setData({
      searchContent:"",
      searchList:[]
    })
  },
  deleteSearch(){

    wx.showModal({
      title:"确认删除吗？",
      success:(res)=>{
        if(res.confirm){
          this.setData({
            historyList:[],
          })
          wx.removeStorageSync('searchHitory')
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})